<?php
class App_Dispatcher
{
    private static function initAutoLoad()
    {

        function __autoload($className)
        {
            
            $classNameArr = explode('_', $className);
            $pathToClass = '';
            $ds = DIRECTORY_SEPARATOR;

            foreach($classNameArr as $partOfPath){
                if($pathToClass){
                    $pathToClass .= $ds;
                }
                $pathToClass .= $partOfPath;
            }
            
            $pathToClass .= '.php';
            
            if(!is_file($pathToClass)){
            	throw new Exception("File -- {$pathToClass} -- No found to include");
            }
            
            require_once $pathToClass;
        }
    }

    
    public static function run()
    {
        self::initAutoLoad();
//         $detect = new App_MobileDetect();
//      	$detect->isMobile();
		App_Config::getInstance();
        $http = App_Http::getInstance();
    	try{
//     		App_CSRFUtil::set();
//     		App_CSRFUtil::validate();
    		
       		$className = 'App_Controller_'.$http->getModuleName().'_'.$http->getControllerName();
       		
       		if($http->getModuleName() == "Admin"){
       			$auth = App_Auth::getInstance()->getInstance();
       			if(!$auth->isAuthAction()){
       				$http->setModuleName("Admin")->setControllerName("Auth")->setActionName("login");
       				
       				$className = 'App_Controller_'.$http->getModuleName().'_'.$http->getControllerName();
       			}
       		}
       		
            $ctrl = new $className();
            $ctrl->dispatch($http->getActionName().'Action');
            
        }catch(Exception $e){
        	
        	$massege = '';
        	if(DISPLAY_EXCEPTIONS){
        		
	        	$massege = $e->getMessage();

        		if(App_View::getInstance()->isXmlHttpRequest()){
        			App_Headers::JSON();
        			echo json_encode(array("error"=>$massege));
        			die();
        		}
//         		die( $massege );
        		
        	}
        	$view = App_View::getInstance();
        	$view->showErrorPage(500,$massege);
        }
    }
}